package com.mg.framework.tiled;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class TileSet {

	private Vector<Tile> tiles = new Vector<Tile>();
	private int firstGid;
	private String name;
	private int transparentColor;
	private TileCutter tileCutter;
	private Rectangle tileDimensions;
	private int tileSpacing;
	private int tileMargin;
	private int tilesPerRow;
	private Bitmap tileSetImage;

	public TileSet() {

	}

	public int getFirstGid() {
		return firstGid;
	}

	public Tile getTile(int i) {
		return tiles.get(i);

	}

	public void setName(String name) {
		this.name = name;
	}

	public void setFirstGid(int firstGid) {
		this.firstGid = firstGid;
	}

	public void setTransparentColor(int trans) {
		transparentColor = trans;
	}

	public void importTileBitmap(String fileName, InputStream in,
			TileCutter cutter) throws Exception {

		Bitmap image = BitmapFactory.decodeStream(in).copy(
				Bitmap.Config.ARGB_8888, true);
		if (image == null) {
			throw new IOException("Failed to load " + fileName);
		}
		importTileBitmap(image, cutter);
	}

	private void importTileBitmap(Bitmap tileBitmap, TileCutter cutter) {

		tileSetImage = tileBitmap;
		tileCutter = cutter;

		cutter.setImage(tileBitmap);

		tileDimensions = new Rectangle(cutter.getTileDimensions());
		if (cutter instanceof BasicTileCutter) {
			BasicTileCutter basicTileCutter = (BasicTileCutter) cutter;
			tileSpacing = basicTileCutter.getTileSpacing();
			tileMargin = basicTileCutter.getTileMargin();
			tilesPerRow = basicTileCutter.getTilesPerRow();
		}

		Bitmap tileImage = cutter.getNextTile();
		while (tileImage != null) {
			Tile tile = new Tile();
			tile.setImage(tileImage);
			addNewTile(tile);
			tileImage = cutter.getNextTile();
		}
	}

	public void addNewTile(Tile t) {
		t.setId(-1);
		addTile(t);
	}

	public int addTile(Tile t) {
		if (t.getId() < 0)
			t.setId(tiles.size());

		if (tileDimensions.width < t.getWidth())
			tileDimensions.width = t.getWidth();

		if (tileDimensions.height < t.getHeight())
			tileDimensions.height = t.getHeight();

		tiles.add(t);
		t.setTileSet(this);

		return t.getId();
	}

	public int getMaxTileId() {
		return tiles.size() - 1;
	}
}
